package com.android.volley.codec;


import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;

/**
 * Created by yinzhiqun on 2015/12/4.
 *
 */
public class YQEncoder extends Coder implements Encoder {

    private YQKey key;

    public YQEncoder(YQKey key) {
        this.key = key;
    }

    @Override
    public byte[] encode(byte[] data,boolean base64) {
//        Log.i("kids",new String(key.getAppid(),4,key.getAppid().length-4));
        //prefix + appid + data
        //YQKey已经处理过，appid包含appidLength
        //除了11645接口发送json字符串，还有11647接口，上传|下载头像，上传|下载|删除语音消息，获取|删除照片

        byte[] dataBuffer = doEncrypt(data,base64);
        byte[] appidBuffer = key.getAppid();
        int totalLength = PREFIX.length + appidBuffer.length + dataBuffer.length;
        byte[] totalBuffer = new byte[totalLength];

        System.arraycopy(PREFIX, 0, totalBuffer, 0, PREFIX.length);
        System.arraycopy(appidBuffer, 0, totalBuffer, PREFIX.length, appidBuffer.length);
        System.arraycopy(dataBuffer, 0, totalBuffer, PREFIX.length + appidBuffer.length, dataBuffer.length);

//        StringBuilder stringBuilder = new StringBuilder();
//        for (byte b : totalBuffer) {
//            stringBuilder.append(Integer.toHexString(b)).append(" ");
//        }
//        Log.w("kids", "加密操作 " + totalBuffer.length + ", " + stringBuilder.toString());
//        Log.w("kids", "加密操作, base64: "+base64);
        return totalBuffer;
    }

    private byte[] doEncrypt(byte[] data,boolean base64) {
        try {
            Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
            IvParameterSpec ivParameterSpec = new IvParameterSpec(key.getSecretKey().getEncoded());
            cipher.init(Cipher.ENCRYPT_MODE, key.getSecretKey(),ivParameterSpec);

            if (base64){
                return encryptBASE64Byte(cipher.doFinal(data));
            }else{
                return cipher.doFinal(data);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return data;
    }


}
